/**
 * 工具模块
 */
import { _decorator, MeshRenderer, Sprite, AudioClip, Layers, UITransformComponent, NodePool, Label, Vec3, easing, tween, assetManager, Texture2D, Node, Prefab, instantiate, SkinnedMeshRenderer, Skeleton, Mesh, Material, sys, SpriteFrame, v3, math, Vec2, ParticleSystem, UITransform, BoxCollider } from 'cc';
import GDef from '../config/GDef';
import GD from '../config/GD';
import { Notifications } from "../easyFramework/notifications";
import { tyqSDK } from '../tyq3.x/tyq-sdk';
import TyqEventMgr from '../tyq3.x/tyq-event-mgr';
import SdkMgr from '../tyq3.x/SdkMgr';
import { EType } from '../tyq3.x/Platform/wechat/WXCustomAd';
class Tool {
    /**
     * 实例化预制体
     * @param key 键名
     */


    public createNode(prePackage: string, prePath: string): Promise<any> {
        // public createNode(prePackage: string,prePath: string) {

        // console.log("createNode:" + prePackage);
        // assetManager.loadBundle(prePackage, function (err,bundle) {
        //     console.log("loadBundle");
        //     if (err) {
        //         console.error(prePackage + '分包加载失败')
        //     }
        //     // 加载模型中的网格资源
        //     bundle.load(prePath, Prefab, function (err, item) {
        //         if (err) {
        //             console.error(err);
        //         }
        //     });
        // });



        return new Promise((resolve, reject) => {
            assetManager.loadBundle(prePackage, function (err, bundle) {
                if (err) {
                    console.error(prePackage + '分包加载失败');
                    reject(err);
                }
                bundle.load(prePath, Prefab, function (err, item) {
                    if (err) {
                        console.error(err);
                        reject(err);
                    }
                    resolve(instantiate(item));
                });
            });
        });
    }

    public loadTexture(prePackage: string, prePath: string): Promise<any> {
        console.log("load " + prePackage + "/" + prePath);
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(prePackage, function (err, bundle) {
                if (err) {
                    console.error(prePackage + '分包加载失败');
                    reject(err);
                }
                bundle.load(prePath + '/texture', Texture2D, function (err, item) {
                    if (err) {
                        console.error(err);
                        reject(err);
                    }
                    resolve(item);
                });
            });
        });
    }

    public loadAsset(prePackage: string, prePath: string, assetType: any): Promise<any> {
        console.log("load " + prePackage + "/" + prePath);
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(prePackage, function (err, bundle) {
                if (err) {
                    console.error(prePackage + '分包加载失败');
                    reject(err);
                }
                bundle.load(prePath, assetType, function (err, item) {
                    if (err) {
                        console.error(err);
                        reject(err);
                    }
                    resolve(item);
                });
            });
        });
    }

    public initSkinMesh(skinnedMeshRender: SkinnedMeshRenderer, packagePath: string, meshPath: string, materialPath: string, skePath: string) {
        var self = this;
        return new Promise((resolve, reject) => {
            if (skinnedMeshRender) {
                assetManager.loadBundle(packagePath, function (err, bundle) {
                    if (err) {
                        console.log(packagePath + '分包加载失败')
                    }
                    // 加载模型中的网格资源
                    // console.log("加载模型中的网格资源");
                    bundle.load(meshPath, Mesh, function (err, item) {
                        if (err) {
                            console.error(err);
                            return;
                        }
                        skinnedMeshRender.mesh = item;
                        // 加载模型中的材质资源
                        // console.log("加载模型中的材质资源");
                        bundle.load(materialPath, Material, function (err, item) {
                            if (err) {
                                console.error(err);
                                return;
                            }
                            skinnedMeshRender.material = item;
                            // 加载模型中的骨骼
                            // console.log("加载模型中的骨骼");
                            bundle.load(skePath, Skeleton, function (err, item) {
                                if (err) {
                                    console.error(err);
                                    return;
                                }
                                skinnedMeshRender.skeleton = item;
                                resolve(skinnedMeshRender);
                            });
                        });
                    });
                });
            }
            else reject();
        });
    }

    public getDistance(p1, p2) {
        return p2.clone().subtract(p1.clone()).length();
    }
    public loadSprite(prePackage: string, prePath: string): Promise<any> {
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(prePackage, function (err, bundle) {
                if (err) {
                    console.error(prePackage + '分包加载失败');
                    reject(err);
                }
                bundle.load(prePath, SpriteFrame, function (err, item) {
                    if (err) {
                        console.error(err);
                        reject(err);
                    }
                    resolve(item);
                });
            });
        });
    }
    public playSmoke(parent: Node, pos: Vec3, layer: number = Layers.Enum.DEFAULT) {
        let self = this;
        assetManager.loadBundle(GDef.pack2, function (err, bundle) {
            if (err) {
                console.error('pack2分包加载失败');
            }
            bundle.load(GDef.preSmoke, Prefab, function (err, item) {
                if (err) {
                    console.error(err);
                }
                if (!GDef.nodeSmoke) GDef.nodeSmoke = instantiate(item);
                GDef.nodeSmoke.parent = parent;
                //设置layer
                GDef.nodeSmoke.walk(function (target) {
                    if (target.layer != layer) {
                        target.layer = layer;
                    }
                });
                for (let i = 0; i < GDef.nodeSmoke.children.length; i++) {
                    GDef.nodeSmoke.children[i].getComponent(ParticleSystem)?.stop();
                    GDef.nodeSmoke.children[i].getComponent(ParticleSystem)?.clear();
                }
                GDef.nodeSmoke.setPosition(v3(pos.x, pos.y + 0.2, pos.z + 0.02));
                self.playSmokeAni(GDef.nodeSmoke);
            });
        });
    }
    public playSmokeAni(nodeSmoke: Node) {
        for (let i = 0; i < nodeSmoke.children.length; i++) {
            nodeSmoke.children[i].active = true;
            nodeSmoke.children[i].getComponent(ParticleSystem).enabled = true;
            nodeSmoke.children[i].getComponent(ParticleSystem).play();
        }
    }

    public playPiaodai(parent: Node) {
        let self = this;
        assetManager.loadBundle(GDef.pack2, function (err, bundle) {
            if (err) {
                console.error('pack2分包加载失败');
            }
            bundle.load(GDef.prePiaodai, Prefab, function (err, item) {
                if (err) {
                    console.error(err);
                }
                if (!GDef.nodePiaodai) GDef.nodePiaodai = instantiate(item);
                GDef.nodePiaodai.parent = parent;
                GDef.nodePiaodai.active = true;
                self.playPiaodaiAni(GDef.nodePiaodai);
            });
        });
    }
    public playPiaodaiAni(nodeSmoke: Node) {
        nodeSmoke.getComponent('sp.Skeleton').loop = true;
        nodeSmoke.getComponent('sp.Skeleton').premultipliedAlpha = false;
        let spTrackEntry = nodeSmoke.getComponent('sp.Skeleton').setAnimation(0, 'piaodai', false);
        nodeSmoke.getComponent('sp.Skeleton').setCompleteListener((event) => {
            GDef.nodePiaodai.active = false;
        });
    }
    public playPD(parent: Node) {
        let self = this;
        if (!GDef.poolPD) {
            GDef.poolPD = new NodePool();
        }
        if (GDef.poolPD.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            GDef.nodePD = GDef.poolPD.get();
            GDef.nodePD.parent = parent;
            GDef.nodePD.active = true;
            this.playPDAni(GDef.nodePD);
        }
        else {
            assetManager.loadBundle(GDef.pack2, function (err, bundle) {
                if (err) {
                    console.error('pack2分包加载失败');
                }
                bundle.load(GDef.prePD, Prefab, function (err, item) {
                    if (err) {
                        console.error(err);
                    }
                    if (!GDef.nodePD) {
                        GDef.nodePD = instantiate(item);
                        GDef.nodePD.parent = parent;
                    }
                    GDef.nodePD.active = true;
                    self.playPDAni(GDef.nodePD);
                });
            });
        }
    }
    public playPDAni(nodeSmoke: Node) {
        nodeSmoke.getComponent('sp.Skeleton').loop = false;
        nodeSmoke.getComponent('sp.Skeleton').premultipliedAlpha = false;
        nodeSmoke.getComponent('sp.Skeleton').setAnimation(0, 'animation', false);
        nodeSmoke.getComponent('sp.Skeleton').setCompleteListener((event) => {
            GDef.poolPD.put(GDef.nodePD);
        });
    }



    public showYiLong(parent: Node) {
        let self = this;
        assetManager.loadBundle(GDef.pack2, function (err, bundle) {
            if (err) {
                console.error('pack2分包加载失败');
            }
            bundle.load(GDef.preYilong, Prefab, function (err, item) {
                if (err) {
                    console.error(err);
                }
                if (!GDef.nodeYiLong) GDef.nodeYiLong = instantiate(item);
                GDef.nodeYiLong.parent = parent;
                GDef.nodeYiLong.active = true;
                GDef.nodeYiLong.getComponent("preYiLong").show();
                self.setModelShadow(GDef.nodeYiLong, true);


            });
        });
    }
    public hideYiLong() {
        if (GDef.nodeYiLong) GDef.nodeYiLong.active = false;
    }



    public showLajitong(parent: Node) {
        var self = this;
        if (GDef.nodeLajitong) {
            GDef.nodeLajitong.parent = parent;
            GDef.nodeLajitong.active = true;
        }
        else {
            this.createNode(GDef.pack2, GDef.preLajitong).then((nodeDamage) => {
                nodeDamage.setScale(v3(0.1, 0.1, 0.1));
                nodeDamage.setPosition(GDef.posLajitong);
                nodeDamage.parent = parent;
                nodeDamage.active = true;
                GDef.nodeLajitong = nodeDamage;
                let com: BoxCollider = GDef.nodeLajitong.addComponent(BoxCollider);
                com.size = v3(6, 6, 6);
                com.center = v3(0, 3, 0);
                self.setModelShadow(GDef.nodeLajitong, true);
            });
        }
    }
    public hideLajitong() {
        if (GDef.nodeLajitong) GDef.nodeLajitong.active = false;
    }


    //3D的蛋
    public addEgg(parent: Node, tid: number) {
        let self = this;
        if (!GDef.poolEgg) {
            GDef.poolEgg = new NodePool();
        }
        if (GDef.poolEgg.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            let nodeEgg = GDef.poolEgg.get();
            nodeEgg.parent = parent;
            this.playEgg(nodeEgg, tid);
        }
        else {
            this.createNode(GDef.pack2, GDef.preEgg).then((nodeDamage) => {
                nodeDamage.parent = parent;
                this.playEgg(nodeDamage, tid);
            });
        }
    }
    public playEgg(nodeSmoke: Node, tid: number) {

        //材质
        let jsonArm = jsonTables.getJsonTableObj("dino", tid);
        let material = new Material();
        material.copy(jsonArm.quality == 1 ? GDef.materialNormalSrc : GDef.materialLightSrc);
        this.loadAsset(GDef.pack2, GDef.textureEgg, Texture2D).then((texture) => {
            material.setProperty("mainTexture", texture);
            this.setModelMaterial(nodeSmoke, material);
        });

        this.setModelShadow(nodeSmoke, true);
        let scale = jsonArm.quality == 1 ? 0.2 : 0.3;
        nodeSmoke.setScale(v3(scale, scale, scale));
        nodeSmoke.setPosition(v3(0, 0, 0));
        nodeSmoke.active = true;
        tween(nodeSmoke).parallel(
            tween().by(1, { position: v3(0.5, 0, 0) }),
            tween().by(1, { eulerAngles: v3(0, 0, -720) }),
        ).call(() => {
            GD.addEgg(tid, nodeSmoke);
        }).set({ scale: v3(0, 0, 0) }).delay(1).call(() => {
            GDef.poolEgg.put(nodeSmoke);
        }).start();
    }
    //按钮的蛋
    public createBtnEgg(parent: Node, tid: number, time: number, node3D: Node, useAni: boolean = true) {
        if (!GDef.poolBtnEgg) {
            GDef.poolBtnEgg = new NodePool();
        }
        if (GDef.poolBtnEgg.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            let node = GDef.poolBtnEgg.get();
            node.getComponent("preBtnEgg").init(tid, time, parent, node3D, useAni);

        }
        else {
            this.createNode(GDef.pack2, GDef.preBtnEgg).then((nodeDamage) => {
                console.log("create egg:" + time);
                nodeDamage.getComponent("preBtnEgg").init(tid, time, parent, node3D, useAni);
            });
        }
    }



    public setModelShadow(node: Node, bol: boolean) {
        let skinnedMeshRenderer = node.getComponentsInChildren(SkinnedMeshRenderer);

        for (let i = 0; i < skinnedMeshRenderer.length; i++) {
            skinnedMeshRenderer[i].shadowCastingMode = 1;
            skinnedMeshRenderer[i].setUseBakedAnimation(bol);
        }

        let meshRenderer = node.getComponentsInChildren(MeshRenderer);

        for (let i = 0; i < meshRenderer.length; i++) {
            meshRenderer[i].shadowCastingMode = 1;
            meshRenderer[i].lightmapSettings.bakeable = bol;
        }
    }
    public setModelMaterial(node: Node, mat: Material) {
        let skinnedMeshRenderer = node.getComponentsInChildren(SkinnedMeshRenderer);

        for (let i = 0; i < skinnedMeshRenderer.length; i++) {
            skinnedMeshRenderer[i].material = mat;
        }

        let meshRenderer = node.getComponentsInChildren(MeshRenderer);

        for (let i = 0; i < meshRenderer.length; i++) {
            meshRenderer[i].material = mat;
        }
    }

    public playCoin(parent: Node, startPos: Vec3, endPos: Vec3, cb: any) {
        let self = this;
        let startPos2 = parent.getComponent(UITransformComponent)?.convertToNodeSpaceAR(startPos);
        assetManager.loadBundle(GDef.pack2, function (err, bundle) {
            if (err) {
                console.error('pack2分包加载失败');
            }
            bundle.load(GDef.preJinbi, Prefab, function (err, item) {
                if (err) {
                    console.error(err);
                }
                if (!GDef.poolCoin) {
                    GDef.poolCoin = new NodePool();
                }
                for (let i = 0; i < 10; i++) {
                    let node = null;
                    if (GDef.poolCoin.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                        node = GDef.poolCoin.get();
                    }
                    else node = instantiate(item);
                    node.parent = parent;
                    let pos2 = v3(startPos2.x + Math.cos(i * 40) * 150, startPos2.y + Math.sin(i * 40) * 150, 0);
                    tween(node)
                        .set({ position: startPos2 })
                        .to(0.3, { position: pos2 }, { easing: easing.sineOut })
                        .delay(0.1)
                        .to(self.getDistance(pos2, endPos) * 0.001, { position: self.jumpTo_v3(endPos, 50) }, { easing: easing.sineInOut })
                        .call(() => {
                            if (i == 0 && cb) cb();
                            GDef.poolCoin.put(node);
                        })
                        .start();

                }
            });
        });
    }
    public playAttacked(parent: Node) {
        var self = this;
        let nodeDamage = null;
        if (!GDef.poolAttacked) {
            GDef.poolAttacked = new NodePool();
        }
        if (GDef.poolAttacked.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            nodeDamage = GDef.poolAttacked.get();
            // nodeDamage.setScale(v3(0.2,0.2,0.2));
            nodeDamage?.setPosition(v3(0, 0.2, 0.1));
            nodeDamage.parent = parent;
            tween(nodeDamage).delay(2).removeSelf().start();
        }
        else {
            this.createNode(GDef.pack2, GDef.preAttacked).then((nodeDamage) => {
                // nodeDamage.setScale(v3(0.2,0.2,0.2));
                nodeDamage?.setPosition(v3(0, 0.2, 0.1));
                nodeDamage.parent = parent;
                tween(nodeDamage).delay(2).call(() => {
                    GDef.poolAttacked.put(nodeDamage);
                }).start();
            });
        }
    }


    initArm(__id: number, parent: Node, type: number, pos: Vec3, eulerAngles: Vec3, jsonArmType: Object, jsonArm: Object, cellId: number, layer: any = null, scale: any = null): Promise<any> {
        return new Promise((resolve, reject) => {
            if (GDef.poolArm.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                let nodeArm = GDef.poolArm.get();
                console.log("initArm 通过pool:" + nodeArm);
                if (layer) {
                    nodeArm.layer = layer;
                }
                else nodeArm.layer = Layers.Enum.DEFAULT;
                nodeArm.parent = parent;
                if (layer) nodeArm.getComponent("preArm").setLayer(layer);
                else nodeArm.getComponent("preArm").setLayer(Layers.Enum.DEFAULT);
                if (scale) nodeArm.getComponent("preArm").setScale(scale);
                else nodeArm.getComponent("preArm").setScale(-1);
                nodeArm.getComponent("preArm").init(parent, type, pos, eulerAngles, __id, jsonArmType, jsonArm, cellId);

                resolve(nodeArm);
            } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
                console.log("initArm 通过Create");
                this.createNode(GDef.pack1, GDef.preArm).then((node) => {
                    node.parent = parent;
                    if (layer) {
                        node.layer = layer;
                    }
                    else node.layer = Layers.Enum.DEFAULT;
                    if (layer) node.getComponent("preArm").setLayer(layer);
                    if (scale) node.getComponent("preArm").setScale(scale);
                    node.getComponent("preArm").init(parent, type, pos, eulerAngles, __id, jsonArmType, jsonArm, cellId);
                    resolve(node);
                }).catch(err => {
                    console.error(err);
                    return null;
                });
            }
        });
    }


    public jumpTo_v3(to: Vec3, height: number): Readonly<Vec3> {
        return { value: to, progress: this._jumpTo_progress(3, height) } as any as Vec3;
    }
    public jumpTo_v2(to: Vec3, height: number): Readonly<Vec2> {
        return { value: to, progress: this._jumpTo_progress(2, height) } as any as Vec2;
    }
    public _jumpTo_progress(max: number, height: number): (from: number, to: number, cur: number, pcs: number) => number {
        let i = max;
        let heightSqrt = Math.sqrt(height);
        return (from: number, to: number, cur: number, pcs: number) => {

            // 使用序列耦合区分xyz轴: 1: x, 2: y, 3: z
            if (i >= max) i = 1;
            else i++;

            // let rsl = from + (to - from) * pcs; // lerp
            let rsl = math.lerp(from, to, pcs);

            if (i === 2) { // y轴的增量算法
                let du = Math.abs(1 - pcs * 2); // [0,1] > [1,0,1]
                rsl += height - Math.pow(heightSqrt * du, 2);
            }

            return rsl;
        };
    }

    protected emit(eKey, ...parameters: any[]) {
        let a = Notifications.emit(eKey, ...parameters);
        if (a) {
            return a;
        }
    }

    public createDamageNumber(num: number, prearm: preArm): void {
        var self = this;
        let nodeDamage = null;
        if (!GDef.poolDamage) {
            GDef.poolDamage = new NodePool();
        }
        if (GDef.poolDamage.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            nodeDamage = GDef.poolDamage.get();
            nodeDamage.parent = GDef.getRoot().getComponent('gameMgr').nodeDamagePanel;
            nodeDamage.getComponent(Label).string = '$' + num;
            let distance: any = (nodeDamage.position.z + 7) * 0.12;
            this.setPos(nodeDamage, prearm.nodeHpPos, v3((Math.random() - 0.5) * 40, (Math.random() - 0.5) * 40, 0), v3(distance, distance, distance));
            tween(nodeDamage).set({ scale: v3(0, 0, 0) }).to(0.5, { scale: v3(1, 1, 1) }, { easing: easing.cubicOut }).call(() => {
                GDef.poolDamage.put(nodeDamage);
            }).start();
        }
        else {
            this.createNode(GDef.pack1, GDef.preDamage).then((node) => {
                nodeDamage = node;
                node.parent = GDef.getRoot().getComponent('gameMgr').nodeDamagePanel;
                node.getComponent(Label).string = '$' + num;
                let distance: any = (node.position.z + 7) * 0.12;
                this.setPos(node, prearm.nodeHpPos, v3((Math.random() - 0.5) * 40, (Math.random() - 0.5) * 40, 0), v3(distance, distance, distance));
                tween(node).set({ scale: v3(0, 0, 0) }).to(0.5, { scale: v3(1, 1, 1) }, { easing: easing.cubicOut }).call(() => {
                    GDef.poolDamage.put(node);
                }).start();
            });
        }
    }
    setPos(node: Node, nodeHpPos: Node, pos: Vec3, scale: Vec3): void {
        if (!node) return;
        let _v3_0: Vec3 = new Vec3(0, 0, 0);
        nodeHpPos.getWorldPosition(_v3_0);
        GDef.getCamera().convertToUINode(_v3_0, node.parent, _v3_0);
        node.setPosition(v3(_v3_0.x + pos.x, _v3_0.y + pos.y, _v3_0.z + pos.z));
        node.scale = scale;
    }
    getPos(node: Node, nodeHpPos: Node, pos: Vec3): void {
        if (!node) return;
        let _v3_0: Vec3 = new Vec3(0, 0, 0);
        nodeHpPos.getWorldPosition(_v3_0);
        GDef.getCamera().convertToUINode(_v3_0, node.parent, _v3_0);
        return v3(_v3_0.x + pos.x, _v3_0.y + pos.y, _v3_0.z + pos.z);
    }
    formatNum(n: number) {
        if (n < 10000) return n + "";
        else if (n < 10000000) return Math.floor(n / 1000) + "K";
        else if (n < 10000000000) return Math.floor(n / 1000000) + "M";
        else if (n < 10000000000000) return Math.floor(n / 1000000000) + "G";
        else return Math.floor(n / 1000000000000) + "T";
    }

    formatTime(n: number) {
        let hh = Math.floor(n / 3600);
        let mm = Math.floor((n % 3600) / 60);
        let ss = Math.floor(n % 60);
        return hh + ":" + this.fixedNum(mm, 2) + ":" + this.fixedNum(ss, 2);
    }

    fixedNum(num: number, length: number) {
        return (Array(length).join('0') + num).slice(-length);
    }


    public playEffect(fileName: string) {
        let self = this;
        if (GD.audioEnable) {
            if (GDef.soundResouces[fileName]) {
                GDef.audioMgr.playOneShot(GDef.soundResouces[fileName]);
            }
            else {
                assetManager.loadBundle("AudioClip", (err, bundle) => {
                    bundle.load(fileName, AudioClip, function (err, sound) {
                        if (err) {
                            console.error(err);
                            return;
                        }
                        GDef.soundResouces[fileName] = sound;
                        if (GDef.soundResouces[fileName]) {
                            let tt = new Date().getTime();
                            if (!GDef.soundPlayTime[fileName] || tt - GDef.soundPlayTime[fileName] > 100) {
                                GDef.soundPlayTime[fileName] = tt;
                                GDef.audioMgr.playOneShot(GDef.soundResouces[fileName]);
                            }
                        }
                    });
                });
            }
        }
    }
    /**
       * @description 播放音乐（默认循环）
       * @param {string} fileName
       */
    public playMusic(bool: boolean) {
        let fileName = "bgm";
        let self = this;

        if (GDef.soundResouces[fileName]) {
            let audioClicp = this.isCanPlay(fileName);
            if (audioClicp) {
                GDef.audioMgr.clip = audioClicp;
                if (bool) {
                    GDef.audioMgr.play();
                } else {
                    GDef.audioMgr.stop();
                }
            }
        }
        else {
            assetManager.loadBundle("AudioClip", (err, bundle) => {
                bundle.load(fileName, AudioClip, function (err, sound) {
                    if (err) {
                        console.error(err);
                        return;
                    }
                    GDef.soundResouces[fileName] = sound;
                    let audioClicp = self.isCanPlay(fileName);
                    if (audioClicp) {
                        GDef.audioMgr.clip = audioClicp;
                        if (bool) {
                            GDef.audioMgr.play();
                        } else {
                            GDef.audioMgr.stop();
                        }
                    }
                });
            });
        }
    }
    public isCanPlay(fileName: string) {
        if (!GD.audioEnable) {
            console.log("处于静音");
            return null;
        }
        let file = GDef.soundResouces[fileName];
        if (!file) {
            console.log('sound: fieName is error, please check it');
            return null;
        }
        return file;
    }
    // update (deltaTime: number) {
    //     // Your update function goes here.
    // }
    grayNode(node: Node, bol: boolean) {
        node.walk(function (target) {
            let spr = target.getComponent(Sprite);
            if (spr) {
                spr.grayscale = bol;
            }
        });
    }

    public showHand(parent: Node, name: string, nodePos: Node = null) {
        console.log("showHand");
        let self = this;
        if (GDef.nodeHand) {
            GDef.nodeHand.parent = parent;
            GDef.nodeHand.active = true;
            self.playHandAni(GDef.nodeHand, name);
            if (nodePos) this.setPos(GDef.nodeHand, nodePos, v3(0, -30, 0), v3(1, 1, 1));
            else GDef.nodeHand.setPosition(v3(0, -30, 0));
        }
        else {
            assetManager.loadBundle(GDef.pack1, function (err, bundle) {
                if (err) {
                    console.error('pack2分包加载失败');
                }
                bundle.load(GDef.preHand, Prefab, function (err, item) {
                    if (err) {
                        console.error(err);
                    }
                    if (!GDef.nodeHand) GDef.nodeHand = instantiate(item);
                    GDef.nodeHand.parent = parent;
                    GDef.nodeHand.active = true;
                    self.playHandAni(GDef.nodeHand, name);
                    if (nodePos) self.setPos(GDef.nodeHand, nodePos, v3(0, -30, 0), v3(1, 1, 1));
                    else GDef.nodeHand.setPosition(v3(0, -30, 0));
                });
            });
        }
    }
    public removeHand() {
        if (GDef.nodeHand) {
            GDef.nodeHand.destroy();
            GDef.nodeHand = null;
        }
    }
    public playHandAni(nodeSmoke: Node, name: string) {
        nodeSmoke.getComponent('sp.Skeleton').loop = false;
        nodeSmoke.getComponent('sp.Skeleton').premultipliedAlpha = false;
        nodeSmoke.getComponent('sp.Skeleton').setAnimation(0, name, true);
    }

    showBanner() {
        if (!this.isInVerify()) {
            let t = tyqSDK.getSwitchValue("tyq_bannerTurns");
            //banner轮播
            if (t > 0) {
                SdkMgr.ins.showBannerTurns(t);
            }
            else SdkMgr.ins.showBanner();
        }
    }
    hideBanner() {
        if (this.tweenBanner) this.tweenBanner.stop();
        this.tweenBanner = null;
        SdkMgr.ins.hideBanner();
    }

    // loadLayerGrid: "loadLayerGrid",
    // //游戏页上方横格子
    // mainLayerTop: "mainLayerTop",
    // //结算界面左右两侧格子
    // rewardLeftGrid: "rewardLeftGrid",
    // //结算界面左右两侧格子
    // rewardRightGrid: "rewardRightGrid",
    showGridAD() {
        if (!this.isInVerify() && tyqSDK.getSwitchValue("isShowGrid")) {
            SdkMgr.ins.showWxCustomAd(GDef.wxGridFlag.loadLayerGrid, EType.rect, {
                centerX: 0,
                centerY: 0,
            });
        }
    }
    hideGridAD() {
        SdkMgr.ins.hideWxCustomAd(GDef.wxGridFlag.loadLayerGrid);
    }

    showSideGridAD() {
        if (true || !this.isInVerify() && tyqSDK.getSwitchValue("tyq_gameFire")) {
            SdkMgr.ins.showWxCustomAd(GDef.wxGridFlag.rewardLeftGrid, EType.vertical, {
                left: 0,
                top: 230,
            });
            const tweenTargetVec31 = new Vec3();
            tween(tweenTargetVec31).delay(Math.random() + 1).call(() => {
                SdkMgr.ins.showWxCustomAd(GDef.wxGridFlag.rewardRightGrid, EType.grid, {
                    right: -8,
                    top: 230,
                });
            }).start();
        }
    }
    hideSideGridAD() {
        SdkMgr.ins.hideWxCustomAd(GDef.wxGridFlag.rewardLeftGrid);
        SdkMgr.ins.hideWxCustomAd(GDef.wxGridFlag.rewardRightGrid);
    }

    showTopGridAD() {
        if (!this.isInVerify() && tyqSDK.getSwitchValue("tyq_gametop")) {
            SdkMgr.ins.showWxCustomAd(GDef.wxGridFlag.mainLayerTop, EType.horizontal, {
                top: 0,
            });
        }
    }
    hideTopGridAD() {
        SdkMgr.ins.hideWxCustomAd(GDef.wxGridFlag.mainLayerTop);
    }
    isInVerify() {
        if (tyqSDK.getSwitchValue("wxVerify")) {
            return false;
        }
        return true;
    }
}

export default new Tool;